package dyyx.web;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import dyyx.util.CommUtil;
import dyyx.util.ConfigUtil;
import dyyx.util.JdbcUtil;
import dyyx.util.QueryInfo;

public abstract class WebUtil {
	
	
	private static final String ERROR = "error";
	
	
	
	
	///
	
	public static String getErrorMsg(Map<String, Object> map){
		if(map==null){
			return null;
		}
		Object tmp = map.get(ERROR);
		if(tmp==null){
			return null;
		}
		return tmp.toString();
	}
	
	public static int getInt(HttpServletRequest request,String name,int def){
		String str = request.getParameter(name);
		if(str!=null){
			str = str.trim();
		}
		return CommUtil.getInt(str, def);
	}
	
	public static int getInt(HttpServletRequest request,String name){
		return getInt(request,name,0);
	}

	
	////
	
	public static void conntest(HttpServletRequest request, Map<String, Object> map) throws Exception {
		Connection cn = null;
		try {
			long start = System.currentTimeMillis();
			cn = JdbcUtil.getConn();
			long end = System.currentTimeMillis();
			long time = end - start;

			String url = ConfigUtil.get("url");
			String user = ConfigUtil.get("user");
			String driver = ConfigUtil.get("driver");

			String driverInfo = JdbcUtil.getDriver(url);
			map.put("time", time);
			map.put("url", url);
			map.put("user", user);
			map.put("driver", driver);
			map.put("driverInfo", driverInfo);

			map.put("cn", cn.getClass()+","+cn.toString());
			map.put("autoCommit", cn.getAutoCommit());

		} finally {
			JdbcUtil.close(cn);
		}

	}
	
	
	
	public static void query(HttpServletRequest request, Map<String, Object> map) throws Exception {
		String sql = request.getParameter("sql0");
		int maxRows = getInt(request,"maxRows",0);
		
		if(CommUtil.isBlank(sql)){
			map.put(ERROR, "sql blank");
			return;
		}
		
		QueryInfo info = new QueryInfo();
		info.sql = sql;
		info.maxRows = maxRows;
		JdbcUtil.query(info);
		map.put("data", info);
	}
	
	public static void update(HttpServletRequest request, Map<String, Object> map) throws Exception {
		String sql = request.getParameter("sql0");
		
		if(CommUtil.isBlank(sql)){
			map.put(ERROR, "sql blank");
			return;
		}
		
		map.put("sql", sql);
		
		Connection cn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try {
			long start = System.currentTimeMillis();
			cn = JdbcUtil.getConn();
			long end = System.currentTimeMillis();
			long time = end - start;
			map.put("connTime", time);

			
			stmt = cn.createStatement();
			start = System.currentTimeMillis();
			int updateResult = stmt.executeUpdate(sql);
			end = System.currentTimeMillis();
		    time = end - start;
			map.put("updateTime", time);
			
			map.put("updateResult", updateResult);


		} finally {
			JdbcUtil.close(rs);
			JdbcUtil.close(stmt);
			JdbcUtil.close(cn);
		}
		
		
	}


}